<!-- eslint-disable vue/no-template-shadow -->
<template>
	<div :class="['filter', { active: isSlot && !isShowExpandIcon }]">
		<h4 class="title sle" v-if="title">{{ title }}</h4>
		<!-- <el-input v-model="filterText" placeholder="输入关键字进行过滤" v-if="isFilter" clearable /> -->
		<el-input v-model="filterText" placeholder="请输入" v-if="isFilter">
			<template #suffix
				><el-icon size="16" :style="{ cursor: 'pointer' }" @click="searchClick"><Search /></el-icon
			></template>
		</el-input>
		<el-scrollbar :style="{ height: title ? `calc(100% - 95px)` : `calc(100% - 56px)` }" v-loading="treeLoading">
			<el-tree
				ref="treeRef"
				:default-expand-all="defaultExpandAll"
				:node-key="id"
				:data="treeData"
				:indent="indent"
				:show-checkbox="multiple"
				:check-strictly="false"
				:current-node-key="!multiple ? defaultValue : ''"
				:highlight-current="!multiple"
				:expand-on-click-node="expandOnClickNode"
				:check-on-click-node="multiple"
				:key="defaultExpandedKeys?.join(',')"
				:default-expanded-keys="defaultExpandedKeys"
				:props="defaultProps"
				:filter-node-method="filterNode"
				:default-checked-keys="multiple ? defaultValue : []"
				@node-click="handleNodeClick"
				@check="handleCheckChange"
			>
				<template #default="{ node, data }" v-if="isSlot">
					<slot name="default" :node="node" :data="data"></slot>
				</template>
			</el-tree>
		</el-scrollbar>
	</div>
</template>

<script setup lang="ts" name="TreeFilter">
import { ref, watch, onBeforeMount, computed } from 'vue';
import { ElTree } from 'element-plus';

// 接收父组件参数并设置默认值
interface TreeFilterProps {
	requestApi?: (data?: any) => Promise<any>; // 请求分类数据的 api ==> 非必传
	params?: any;
	data?: { [key: string]: any }[]; // 分类数据，如果有分类数据，则不会执行 api 请求 ==> 非必传
	title?: string; // treeFilter 标题 ==> 非必传
	id?: string; // 选择的id ==> 非必传，默认为 “id”
	label?: string; // 显示的label ==> 非必传，默认为 “label”
	multiple?: boolean; // 是否为多选 ==> 非必传，默认为 false
	defaultValue?: any; // 默认选中的值 ==> 非必传
	isClickChildren?: boolean;
	isSlot?: boolean;
	isShowExpandIcon?: boolean;
	isFilter?: boolean;
	level?: number;
	defaultExpandAll?: boolean;
	indent?: number;
	defaultExpandedKeys?: string[];
	expandOnClickNode?: boolean;
}
const props = withDefaults(defineProps<TreeFilterProps>(), {
	id: 'id',
	label: 'label',
	multiple: false,
	isFilter: true,
	isShowExpandIcon: false,
	params: {},
	level: 0,
	indent: 16,
	defaultExpandAll: false,
	expandOnClickNode: true
});

const defaultProps = {
	children: 'children',
	label: props.label
};

const filterText = ref<string>('');
const treeRef = ref<InstanceType<typeof ElTree>>();
const treeData = ref<{ [key: string]: any }[]>([]);
const treeDataFilter = ref<{ [key: string]: any }[]>([]);
const treeDataAll = ref<{ [key: string]: any }[]>([]);
const treeLoading = ref(false);
onBeforeMount(async () => {
	if (props.data?.length) return (treeData.value = props.data);
	if (!props.requestApi) return;
	treeLoading.value = true;
	try {
		const { data } = await props.requestApi!(props.params);
		const dataList = data ?? [];
		if (props.multiple) return (treeData.value = dataList);
		treeData.value = [...dataList];
		// const depth = getMaxDepth(dataList);
		// console.clear();
		treeData.value = dataList;
		treeLoading.value = false;
		// if (props.level) {
		// 	treeData.value = filterLvLeq3(dataList);
		// 	// console.log(treeData.value);
		// 	// console.log(filterLvLeq3(data));
		// }
	} catch (error) {
		treeLoading.value = false;
	}
});
// let maxDepth = 0;
// function getMaxDepth(data: any) {
// 	if (data.length === 0) {
// 		return 0; // 如果不是数组或数组为空，返回0
// 	}

// 	function traverse(nodes: any) {
// 		nodes.forEach((node: any) => {
// 			// 如果节点有子节点，递归遍历子节点
// 			if (node.children && node.children.length > 0 && node.lv <= props.level) {
// 				// 递归计算每个元素的深度
// 				const depth = getMaxDepth(node.children);
// 				maxDepth = Math.max(maxDepth, depth);
// 			}
// 		});
// 	}

// 	// 从根节点开始遍历
// 	traverse(data);
// 	return maxDepth + 1; // 返回当前节点的深度 + 1
// }
// const filterLvLeq3 = (data: any) => {
// 	const level = props.level;
// 	const filteredNodes: any = [];
// 	function traverse(nodes: any) {
// 		nodes.forEach((node: any) => {
// 			const dataNodes = JSON.parse(JSON.stringify({ ...node }));
// 			if (node.lv !== level) {
// 				for (let i = 0; i < treeDataAll.value.length; i++) {
// 					if (treeDataAll.value[i].id === dataNodes.parentId) {
// 						Object.assign(dataNodes, {
// 							firstName: treeDataAll.value[i].name
// 						});
// 					}
// 				}
// 				treeDataAll.value.push(dataNodes);
// 			}

// 			if (node.lv === level) {
// 				treeDataFilter.value.push(dataNodes);
// 				node.children = [];
// 			}

// 			node.lv === 1 && filteredNodes.push(node);
// 			// 如果节点有子节点，递归遍历子节点
// 			if (node.children && node.children.length > 0 && node.lv <= level) {
// 				traverse(node.children);
// 			}
// 		});
// 	}

// 	// // 从根节点开始遍历;
// 	// function traverse(nodes) {
// 	// 	nodes.forEach(node => {
// 	// 		if (node.children && node.children.length > 0) {
// 	// 			// 递归遍历子节点
// 	// 			traverse(node.children);
// 	// 			// 置空最后一层 children
// 	// 			if (node.children.length > 0) {
// 	// 				const lastChildren = node.children; // 获取最后一层 children
// 	// 				treeDataFilter.value.push(...lastChildren); // 添加到 extractedChildren
// 	// 				node.children = []; // 置空 children
// 	// 			}
// 	// 		}
// 	// 	});
// 	// }
// 	traverse(data);
// 	return filteredNodes;
// };
watch(filterText, val => {
	treeRef.value!.filter(val);
});

const propsData = computed<any>(() => {
	return props.data;
});

watch(propsData, val => {
	treeData.value = val;
});

// 过滤
const filterNode = (value: string, data: { [key: string]: any }, node: any) => {
	if (!value) return true;
	let parentNode = node.parent,
		labels = [node.label],
		level = 1;
	while (level < node.level) {
		labels = [...labels, parentNode.label];
		parentNode = parentNode.parent;
		level++;
	}
	return labels.some(label => label.indexOf(value) !== -1);
};

interface FilterEmits {
	(e: 'change', value: any): void;
	(e: 'searchClick', value: string): void;
}
const emit = defineEmits<FilterEmits>();

// 搜索
const searchClick = () => {
	emit('searchClick', filterText.value);
};

// 单选
const handleNodeClick = (data: { [key: string]: any }, nodes: any) => {
	if (props.multiple) return;
	if (!props.isClickChildren && data.children && data.children.length > 0) {
		return;
	}
	emit('change', { id: data[props.id], label: data[props.label], ...data, parent: { ...nodes } });
};

// 多选
const handleCheckChange = () => {
	emit('change', treeRef.value?.getCheckedKeys());
};
defineExpose({
	treeDataFilter,
	treeDataAll
});
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
